package com.atguigu.exam.service.impl;


import com.atguigu.exam.entity.Category;
import com.atguigu.exam.entity.Question;
import com.atguigu.exam.exception.ExamException;
import com.atguigu.exam.mapper.CategoryMapper;
import com.atguigu.exam.mapper.QuestionMapper;
import com.atguigu.exam.service.CategoryService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Slf4j
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {
    @Autowired
    private QuestionMapper questionMapper;

    @Override
    public List<Category> getCategroyCount() {
        List<Category> categories = baseMapper.selectList(new LambdaQueryWrapper<Category>().orderByAsc(Category::getSort));
        addCategoryCount(categories);
        return categories;
    }

    private void addCategoryCount(List<Category> categories) {
        List<Map<Long, Long>> categoryCount = questionMapper.getCategoryCount();
        Map<Long, Long> collect = categoryCount.stream().collect(Collectors.toMap(
                k -> k.get("category_id"),
                v -> v.get("count")
        ));
        categories.forEach(v -> {
            Long count = collect.getOrDefault(v.getId(), 0L);
            v.setCount(count);
        });
    }

    @Override
    public List<Category> getCategoryTree() {
        List<Category> categories = baseMapper.selectList(new LambdaQueryWrapper<Category>().orderByAsc(Category::getSort));
        addCategoryCount(categories);
        List<Category> firstLevelCategroy = bulidCategroyTree(categories);
        return firstLevelCategroy;
    }

    private List<Category> bulidCategroyTree(List<Category> categories) {
        Map<Long, List<Category>> categroyMap = categories.stream().collect(Collectors.groupingBy(Category::getParentId));
        categories.forEach(category -> {
            Long id = category.getId();
            List<Category> childrenCategroy = categroyMap.getOrDefault(id, new ArrayList<>());
            category.setChildren(childrenCategroy);
            long sum = childrenCategroy.stream().mapToLong(Category::getCount).sum();
            Long currentCount = category.getCount();
            category.setCount(sum + currentCount);
        });
        List<Category> firstLevelCategory = categories.stream().filter(c -> c.getParentId() == 0).collect(Collectors.toList());
        return firstLevelCategory;
    }
    @Override
    public void addCateGory(Category category) {
        LambdaQueryWrapper<Category> eq = new LambdaQueryWrapper<Category>().eq(Category::getName, category.getName()).eq(Category::getParentId, category
                .getId());
        boolean exists = baseMapper.exists(eq);
        if (exists){
            Category parentId = baseMapper.selectById(category.getParentId());
            throw new ExamException(501,"在父分类"+parentId.getName()+"下，已经存在！请给"+category.getName()+"修改一个其他名字");
        }
        baseMapper.insert(category);
    }

    @Override
    public void updateCategory(Category category) {
        category.setUpdateTime(null);
        LambdaQueryWrapper<Category> ne = new LambdaQueryWrapper<Category>().eq(Category::getName, category.getName()).eq(Category::getParentId, category.getParentId()).ne(Category::getId, category.getId());
        boolean exists = baseMapper.exists(ne);
        if (exists){
            Category parentId = baseMapper.selectById(category.getParentId());
            throw new ExamException(508,"在父分类"+parentId.getName()+"下，已经存在！请给"+category.getName()+"修改一个其他名字");
        }
        baseMapper.updateById(category);
    }

    @Override
    public void deleteCategory(Long id) {
        LambdaQueryWrapper<Category> eq = new LambdaQueryWrapper<Category>().eq(Category::getParentId, id);
        Long count = baseMapper.selectCount(eq);
        if (count>0){
            throw new ExamException(555,"该分类下有子分类，不能删除");
        }
        LambdaQueryWrapper<Question> questionLambdaQueryWrapper = new LambdaQueryWrapper<Question>().eq(Question::getCategoryId, id);
        Long selectCount = questionMapper.selectCount(questionLambdaQueryWrapper);
        if (selectCount>0){
            throw new ExamException(888,"该分类下还有题目，不能删除");
        }
        baseMapper.deleteById(id);
    }


}